<template>
  <!-- 图表容器它一定要有一固定高度 -->
  <div ref="chartRef" class="chart" :style="{ '--chart-height': chartHeight }"></div>
</template>

<script>
import * as echarts from 'echarts'
import mix from './mixin'
export default {
  mixins: [mix],
  name: 'bar',
  props: {
    xAxis: {
      type: Array,
      required: true
    },
    series: {
      type: Array,
      required: true
    },
    title: {
      type: String,
      default: ''
    },
    tooltip: {
      type: Boolean,
      default: true
    },
    legend: {
      type: Array,
      default: () => []
    },
    grid: {
      type: Object,
      default: () => ({
        left: 30,
        top: 10,
        right: 20,
        bottom: 30
      })
    },
    height: {
      type: [Number, String],
      default: 'inherit'
    }
  },
  computed: {
    chartHeight() {
      return typeof this.height === 'number' ? this.height + 'px' : this.height
    }
  },
  mounted() {
    // 初始化echarts实例
    this.myChart = echarts.init(this.$refs.chartRef, '', { renderer: 'canvas' })
    this.myChart.setOption({
      title: {
        show: this.title.length === 0 ? false : true,
        text: this.title
      },
      tooltip: {
        show: this.tooltip,
        backgroundColor: 'rgba(50,50,50,0.7)', // 提示框浮层的背景颜色。
        borderColor: '#333', // 提示框浮层的边框颜色。
        borderWidth: 0, // 提示框浮层的边框宽。
        padding: 5, // 提示框浮层内边距
        // 提示框浮层的文本样式
        textStyle: {
          color: '#fff',
          fontSize: 16
        },
        // 格式化它是支持html的
        formatter: function (arg) {
          const seriesName = arg.seriesName
          const name = arg.name
          const value = arg.value
          return `<div>【${seriesName}】- ${name} : ${value} 元</div>`
        }
      },
      legend: {
        show: this.legend.length === 0 ? false : true,
        data: this.legend,
        right: 10
      },
      xAxis: {
        data: this.xAxis
      },
      yAxis: {
        type: 'value'
      },
      grid: {
        show: false,
        ...this.grid
      },
      // 坐标系,它可以有多个
      series: this.series
    })
  },
  beforeDestroy() {
    // 销毁实例
    this.myChart && this.myChart.dispose()
    this.myChart = null
  }
}
</script>

<style lang="scss" scoped>
.chart {
  height: var(--chart-height);
}
</style>
